package com.eightgroups.tces.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.eightgroups.sys.entity.RolePermission;
import com.eightgroups.sys.entity.ZNodes;
import com.eightgroups.tces.entity.Indicator;
import com.eightgroups.tces.entity.QtypeIndicator;
import com.eightgroups.tces.mapper.IndicatorMapper;
import com.eightgroups.tces.mapper.QtypeIndicatorMapper;
import com.eightgroups.tces.service.IIndicatorService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.eightgroups.tces.service.IQtypeIndicatorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 指标 服务实现类
 * </p>
 *
 * @author zzc2016.cn
 * @since 2017-11-13
 */
@Service
public class IndicatorServiceImpl extends ServiceImpl<IndicatorMapper, Indicator> implements IIndicatorService {

    @Autowired
    private IndicatorMapper indicatorMapper;
    @Autowired
    private QtypeIndicatorMapper qtypeIndicatorMapper;
    @Autowired
    private IQtypeIndicatorService iQtypeIndicatorService;
    @Override
    public List<ZNodes> findIndicatorZTreeNodes(Long pid) {
        EntityWrapper<Indicator> indicatorEntityWrapper = new EntityWrapper<>();
        indicatorEntityWrapper.orderBy("sort", true);
        List<Indicator> indicators = indicatorMapper.selectList(indicatorEntityWrapper);

        // 查询角色拥有那些权限
        EntityWrapper<QtypeIndicator> qtypeIndicatorEntityWrapper = new EntityWrapper<>();
        qtypeIndicatorEntityWrapper.eq("qid", pid);
        List<QtypeIndicator> qtypeIndicators = qtypeIndicatorMapper.selectList(qtypeIndicatorEntityWrapper);

        List<ZNodes> zNodes = new ArrayList<>();
        indicators.forEach(p -> {
            ZNodes node = new ZNodes();
            BeanUtils.copyProperties(p, node);
            // 设置展开节点
            if (p.getPid() == 0) {
                node.setOpen(true);
            }
            // 设置角色拥有的权限选中
            if (qtypeIndicators.size()>0){
                qtypeIndicators.forEach(qi -> {
                    if (p.getId() == qi.getIid()) {
                        node.setChecked(true);
                    }
                });
            }else {
                if (p.getId() == pid) {
                    node.setChecked(true);
                }
            }

            zNodes.add(node);
        });
        return zNodes;
    }

    @Override
    public boolean modifyQtypeIndicator(List<QtypeIndicator> qtypeIndicators) {
        // 删除原表
        EntityWrapper<QtypeIndicator> qtypeIndicatorEntityWrapper = new EntityWrapper<>();
        qtypeIndicatorEntityWrapper.eq("qid", qtypeIndicators.get(0).getQid());
        qtypeIndicatorMapper.delete(qtypeIndicatorEntityWrapper);

        // 新增并返回处理结果
        return iQtypeIndicatorService.insertBatch(qtypeIndicators);
    }
}
